package com.self.springframework.beans.factory.support;

import com.self.springframework.beans.factory.DisposableBean;
import com.self.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DisposableBeanAdapter implements DisposableBean {

    private final Object bean;
    private final String beanName;
    private final BeanDefinition beanDefinition;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.beanDefinition = beanDefinition;
    }

    @Override
    public void destroy() {
        // 1.实现DisposableBean接口
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }

        // 2.配置destroy-method方法
        String destroyMethodName = beanDefinition.getDestroyMethodName();
        if ((destroyMethodName != null && !destroyMethodName.equals("")) && !(bean instanceof DisposableBean)) {
            try {
                Method method = beanDefinition.getBeanClass().getMethod(destroyMethodName);
                method.invoke(bean);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
